from PyQt5.QtWidgets import QDialog, QGridLayout, QLabel, QComboBox, QPushButton, QCheckBox

from system import run_command


class AddModule(QDialog):
    def __init__(self):
        super().__init__()
        self.initUI()

    def load_packet(self):
        file = run_command('kdialog --getopenfilename --title "Выберите файл модуля"')
        if file:
            if 'Загрузите интернет-пакет...' in self.packets_combobox_items:
                self.packets_combobox_items.remove('Загрузите интернет-пакет...')
            self.packets_combobox_items.append(file)
            self.packets_combobox.clear()
            self.packets_combobox.addItems(self.packets_combobox_items)
            self.packet_loaded = True
            self.print_and_scan_checkbox.setChecked(False)

    def print_and_scan_checkbox_state_change(self):
        if self.print_and_scan_checkbox.isChecked() and self.packet_loaded:
            self.create_button.setEnabled(True)
        else:
            self.create_button.setEnabled(False)

    def initUI(self):
        grid = QGridLayout()
        self.setLayout(grid)

        self.packet_loaded = False
        grid.addWidget(QLabel('Интернет-пакет'), 0, 0)
        self.packets_combobox = QComboBox()
        self.packets_combobox_items = ['Загрузите интернет-пакет...']
        self.packets_combobox.addItems(self.packets_combobox_items)
        grid.addWidget(self.packets_combobox, 1, 0)
        load_packet_button = QPushButton('Загрузить')
        load_packet_button.clicked.connect(self.load_packet)
        grid.addWidget(load_packet_button, 1, 1)
        choose_packet_label = QLabel('Для выбора экзамена выберите интернет-пакет или загрузите новый')
        grid.addWidget(choose_packet_label, 2, 0, 1, 2)
        choose_module_label = QLabel('<b>Выберите модуль для добавления</b>')
        grid.addWidget(choose_module_label, 3, 0)
        self.print_and_scan_checkbox = QCheckBox('Печать и сканирование в аудитории')
        self.print_and_scan_checkbox.stateChanged.connect(self.print_and_scan_checkbox_state_change)
        grid.addWidget(self.print_and_scan_checkbox, 4, 0)
        cancel_button = QPushButton('Отмена')
        cancel_button.clicked.connect(lambda: self.reject())
        grid.addWidget(cancel_button, 5, 0)
        self.create_button = QPushButton('Создать')
        self.create_button.clicked.connect(lambda: self.accept())
        self.create_button.setDisabled(True)
        grid.addWidget(self.create_button, 5, 1)

        self.setMinimumWidth(600)
        self.setWindowTitle('Добавление модуля')
